package top.kaoshanji.p1ch03b;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.MembershipKey;

/**
 * 代码清单 p1ch03b-16：进行组播消息的客户端实现
 * 执行失败...
 * author kaoshanji
 * ^_^
 * create time 2025/1/12 16:37
 */
public class DatagramChannelExample02 {

    private static final Logger logger = LogManager.getLogger(DatagramChannelExample02.class);

    public static void main(String[] args) throws IOException {
        logger.info("...代码清单 p1ch03b-16：进行组播消息的客户端实现...");

        NetworkInterface ni = NetworkInterface.getByName("eth1");
        int port = 5000;
        try (DatagramChannel dc = DatagramChannel.open(StandardProtocolFamily.INET6)
                .setOption(StandardSocketOptions.SO_REUSEADDR, true)
                .bind(new InetSocketAddress(port))
                .setOption(StandardSocketOptions.IP_MULTICAST_IF, ni)){

            InetAddress group = InetAddress.getByName("224.0.0.2");
            MembershipKey key = dc.join(group, ni);
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            dc.receive(buffer);
            buffer.flip();
            byte[] data = new byte[buffer.limit()];
            buffer.get(data);
            String str = new String(data);
            System.out.println(str); // 输出时间
            key.drop();
        }

    }

}
